<?php
declare (strict_types = 1);

namespace app\common;

use think\Session;
use app\admin\model\AdminUser;

class MenuHelper
{
    /**
     * 获取用户菜单
     */
    public static function getUserMenu()
    {
        $userId = Session::get('admin_id');
        if (!$userId) {
            return [];
        }
        
        $user = AdminUser::with('role')->find($userId);
        if (!$user) {
            return [];
        }
        
        // 检查是否是超级管理员
        $isSuperAdmin = false;
        if ($user->role && $user->role->role_code === 'super_admin') {
            $isSuperAdmin = true;
        }
        
        // 如果是超级管理员，返回全部菜单
        if ($isSuperAdmin) {
            return self::getAllMenus();
        }
        
        // 获取用户权限
        $userPermissions = [];
        if ($user->role) {
            // 获取角色的权限
            $rolePermissions = \think\Db::name('role_permissions')
                ->alias('rp')
                ->join('permissions p', 'rp.permission_id = p.id')
                ->where('rp.role_id', $user->role->id)
                ->where('p.is_menu', 1)
                ->column('p.permission_code');
            $userPermissions = $rolePermissions;
        }
        
        // 根据权限过滤菜单
        return self::filterMenusByPermissions($userPermissions);
    }
    
    /**
     * 获取所有菜单配置（精简版）
     */
    private static function getAllMenus()
    {
        return [
            [
                'name' => '数据总览',
                'icon' => 'layui-icon layui-icon-home',
                'url' => 'admin/dashboard/index',
                'permission' => 'dashboard',
                'active_page' => 'dashboard'
            ],
            [
                'name' => '系统管理',
                'icon' => 'layui-icon layui-icon-set',
                'permission' => 'system_manage',
                'active_page' => 'settings',
                'children' => [
                    [
                        'name' => '管理员管理',
                        'url' => 'admin/settings/users',
                        'permission' => 'user_manage'
                    ],
                    [
                        'name' => '角色管理',
                        'url' => 'admin/settings/roles',
                        'permission' => 'role_manage'
                    ],
                    [
                        'name' => '权限管理',
                        'url' => 'admin/settings/permissions',
                        'permission' => 'permission_manage'
                    ],
                    [
                        'name' => '操作日志',
                        'url' => 'admin/settings/logs',
                        'permission' => 'log_view'
                    ],
                    [
                        'name' => '个人资料',
                        'url' => 'admin/settings/profile',
                        'permission' => 'profile_manage'
                    ],
                    [
                        'name' => '修改密码',
                        'url' => 'admin/settings/changepassword',
                        'permission' => 'password_change'
                    ]
                ]
            ]
        ];
    }
    
    /**
     * 根据权限过滤菜单
     */
    private static function filterMenusByPermissions($userPermissions)
    {
        $allMenus = self::getAllMenus();
        $filteredMenus = [];
        
        foreach ($allMenus as $menu) {
            // 检查主菜单权限
            if (in_array($menu['permission'], $userPermissions)) {
                $filteredMenu = $menu;
                
                // 如果有子菜单，过滤子菜单
                if (isset($menu['children'])) {
                    $filteredChildren = [];
                    foreach ($menu['children'] as $child) {
                        if (in_array($child['permission'], $userPermissions)) {
                            $filteredChildren[] = $child;
                        }
                    }
                    
                    // 如果有可访问的子菜单，才显示主菜单
                    if (!empty($filteredChildren)) {
                        $filteredMenu['children'] = $filteredChildren;
                        $filteredMenus[] = $filteredMenu;
                    }
                } else {
                    // 没有子菜单的直接加入
                    $filteredMenus[] = $filteredMenu;
                }
            }
        }
        
        return $filteredMenus;
    }
    
    /**
     * 生成菜单HTML
     */
    public static function generateMenuHTML($currentPage = '', $currentSubpage = '')
    {
        $menus = self::getUserMenu();
        $html = '';
        
        // 获取当前子页面标识
        $currentSubpage = $currentSubpage ?? (isset($_REQUEST['current_subpage']) ? $_REQUEST['current_subpage'] : '');
        
        foreach ($menus as $menu) {
            $isActive = ($currentPage === ($menu['active_page'] ?? ''));
            $activeClass = $isActive ? 'layui-nav-itemed' : '';
            
            if (isset($menu['children']) && !empty($menu['children'])) {
                // 有子菜单
                $html .= '<li class="layui-nav-item ' . $activeClass . '">';
                $html .= '<a href="javascript:;">';
                $html .= '<i class="' . $menu['icon'] . '" style="margin-right: 8px;"></i>';
                $html .= $menu['name'];
                $html .= '</a>';
                $html .= '<dl class="layui-nav-child">';
                
                foreach ($menu['children'] as $child) {
                    // 检查子菜单是否选中
                    $childActive = '';
                    if ($isActive && isset($child['permission']) && $currentSubpage === $child['permission']) {
                        $childActive = ' class="layui-this"';
                    }
                    
                    $html .= '<dd' . $childActive . '><a href="/index.php?s=/' . $child['url'] . '">' . $child['name'] . '</a></dd>';
                }
                
                $html .= '</dl>';
                $html .= '</li>';
            } else {
                // 没有子菜单
                $html .= '<li class="layui-nav-item ' . $activeClass . '">';
                $html .= '<a href="/index.php?s=/' . $menu['url'] . '">';
                $html .= '<i class="' . $menu['icon'] . '" style="margin-right: 8px;"></i>';
                $html .= $menu['name'];
                $html .= '</a>';
                $html .= '</li>';
            }
        }
        
        return $html;
    }
}